"""
数据集模型
"""
from datetime import datetime
import json
from typing import Dict, List
import pandas as pd
import numpy as np
from .. import db

class Dataset(db.Model):
    """数据集模型类"""
    __tablename__ = 'datasets'

    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(255), nullable=False)  # 存储的文件名
    original_filename = db.Column(db.String(255), nullable=False)  # 原始文件名
    file_path = db.Column(db.String(500), nullable=False)  # 文件完整路径
    file_type = db.Column(db.String(10), nullable=False)  # 'csv' or 'excel'
    
    # 元数据
    row_count = db.Column(db.Integer)
    _column_info = db.Column('column_info', db.Text)  # 列信息：[{"name": "col1", "type": "numeric"}, ...]
    description = db.Column(db.Text)
    
    # 状态跟踪
    status = db.Column(db.String(20), default='raw')  # raw/cleaned/analyzed
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 数据清洗关系
    parent_id = db.Column(db.Integer, db.ForeignKey('datasets.id'), nullable=True)  # 原始数据集ID
    created_by = db.Column(db.Integer, nullable=True)  # 创建者ID，预留字段
    
    # 关系
    analysis_tasks = db.relationship('AnalysisTask', backref='dataset', lazy='dynamic')
    children = db.relationship('Dataset', backref=db.backref('parent', remote_side=[id]), lazy='dynamic')

    @property
    def column_info(self) -> List[Dict]:
        """获取列信息"""
        if self._column_info:
            return json.loads(self._column_info)
        return []

    @column_info.setter
    def column_info(self, value: List[Dict]):
        """设置列信息"""
        if value is not None:
            self._column_info = json.dumps(value)
        else:
            self._column_info = None

    @property
    def columns(self) -> List[str]:
        """获取数据集的列名列表"""
        return [col['name'] for col in self.column_info] if self.column_info else []

    def update_metadata(self, row_count: int, column_info: List[Dict]):
        """
        更新数据集元数据
        
        Args:
            row_count: 数据行数
            column_info: 列信息列表
        """
        self.row_count = row_count
        self.column_info = column_info
        self.updated_at = datetime.utcnow()

    def get_data(self) -> np.ndarray:
        """
        获取数据集的数值型内容（自动识别所有数值型列）
        
        Returns:
            np.ndarray: 只包含数值型列的数据数组
        """
        if self.file_type == 'csv':
            df = pd.read_csv(self.file_path)
        else:
            df = pd.read_excel(self.file_path)
        df_numeric = df.select_dtypes(include=[np.number])
        if df_numeric.shape[1] == 0:
            raise ValueError("No numeric columns found in dataset")
        return df_numeric.to_numpy()

    def to_dict(self) -> Dict:
        """转换为字典格式"""
        return {
            'id': self.id,
            'filename': self.filename,
            'original_filename': self.original_filename,
            'file_type': self.file_type,
            'row_count': self.row_count,
            'columns': self.columns,
            'column_info': self.column_info,
            'status': self.status,
            'description': self.description,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'parent_id': self.parent_id
        }

    def __repr__(self):
        return f'<Dataset {self.filename}>' 